package ch.hearc.ig.android.crudpersonnes.communication;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.util.ByteArrayBuffer;

import ch.hearc.ig.android.crudpersonnes.business.Personne;
import ch.hearc.ig.android.crudpersonnes.screen.LoginActivity;
import ch.hearc.ig.android.crudpersonnes.screen.PersonneListActivity;
import ch.hearc.ig.android.crudpersonnes.screen.R;
import ch.hearc.ig.android.crudpersonnes.screen.tool.PersonneAdapter;
import ch.hearc.ig.android.crudpersonnes.utils.PersonneUtil;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class PersonneServiceCaller extends AsyncTask<String, Integer, String> {

	/*
	 * in case of return of invalidate session the params should be saved and
	 * executate on the next login otherwise theywill be loosed each time the
	 * session is invalidate
	 */
	public static String appUrl;

	private Boolean logOut = false;
	public static Boolean proxy = false;
	private ListFragment listFragment;
	private LoginActivity loginActivity;
	private String invokedService = null;
	private Context curContext = null;

	public PersonneServiceCaller(ListFragment personneListFragment) {
		this.listFragment = personneListFragment;
		this.curContext = listFragment.getActivity();
	}

	public PersonneServiceCaller(LoginActivity loginActivity) {
		this.loginActivity = loginActivity;
		this.curContext = loginActivity;
	}

	public PersonneServiceCaller(PersonneListActivity personneListActivity) {
		this.curContext = personneListActivity;
	}

	public PersonneServiceCaller() {
		// TODO Auto-generated constructor stub
	}

	@SuppressWarnings("finally")
	@Override
	protected String doInBackground(String... params) {
		URL myURL = null;
		String urlTocall = null;
		BufferedInputStream bis = null;
		String returnString = "";
		HttpURLConnection huc = null;

		try {
			// check if its run on yannick's phone identified by the serial
			// or on a other virtual device. removing the app url problem.
			if (android.os.Build.SERIAL.equalsIgnoreCase("014691480601101A")) {
				appUrl = "http://NE-EGE-WEBERY1:8080/CRUDPersonnesBackOffice/";
			} else {
				appUrl = "http://10.0.2.2:8080/CRUDPersonnesBackOffice/";
			}

			Log.v("PersonneServiceCaller", android.os.Build.SERIAL);
			// in the post process I need to now which action we just performed
			invokedService = params[0];
			// I also need to now if we are on the logout as the forwading is
			// different
			if (params[9].equalsIgnoreCase("logout")) {
				logOut = true;
			}

			urlTocall = appUrl + PersonneUtil.constructUrl(params);
			Log.v("URL called", urlTocall);

			myURL = new URL(urlTocall);

			if (!proxy) {
				Log.v("PersonneServiceCaller", "Begin open connection wo proxy");
				huc = (HttpURLConnection) myURL.openConnection();
				Log.v("PersonneServiceCaller", "END open connection wo proxy");
			} else {
				SocketAddress addr = new InetSocketAddress("proxy.he-arc.ch",
						8080);
				Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
				huc = (HttpURLConnection) myURL.openConnection(proxy);
			}
			huc.setConnectTimeout(15 * 1000);

			bis = new BufferedInputStream(huc.getInputStream());
			Log.v("PersonneServiceCaller", "loading input stream");
			ByteArrayBuffer baf = new ByteArrayBuffer(50);
			Log.v("PersonneServiceCaller", "bit ArrayBuffer");
			int current = 0;
			while ((current = bis.read()) != -1) {
				baf.append((byte) current);
			}

			returnString = new String(baf.toByteArray());
			Log.i("Assync Task ok", returnString);

		} catch (Exception e) {

			returnString = e.getMessage();
			Log.i("Assync Task Fail", returnString);
			return null;

		} finally {
			try {
				if (bis != null)
					bis.close();
				return returnString;
			} catch (final IOException e) {
				e.printStackTrace();
				Log.v("error", e.getMessage());
				return null;
			}
		}

	}

	@Override
	protected void onPostExecute(String result) {
		try {
			// check session actif
			if (result.equalsIgnoreCase("Session invalid")) {
				LoginActivity.SESSION_ID = null;

				Toast.makeText(this.curContext, R.string.session_invalide,
						Toast.LENGTH_LONG).show();

				Intent intent = new Intent(curContext, LoginActivity.class);
				curContext.startActivity(intent);

			} else {
				if (this.invokedService.equalsIgnoreCase("ServiceR")) {

					ArrayList<Personne> l_per = null;
					l_per = PersonneUtil.stringJsonToListPersonne(result);
					PersonneAdapter.addPersonne(l_per);

					Log.i("PersonneServiceCaller", "Size of list"
							+ PersonneAdapter.personnes.size());

					ArrayAdapter<Personne> adapter = new ArrayAdapter<Personne>(
							listFragment.getActivity(),
							android.R.layout.simple_list_item_activated_1,
							android.R.id.text1, PersonneAdapter.personnes);
					listFragment.setListAdapter(adapter);
					adapter.notifyDataSetChanged();
					if (l_per != null) {
						if (l_per.isEmpty()) {
							Toast.makeText(listFragment.getActivity(),
									R.string.data_loading_ko, Toast.LENGTH_LONG)
									.show();
						} else {

							Toast.makeText(listFragment.getActivity(),
									R.string.data_loading_ok, Toast.LENGTH_LONG)
									.show();
						}
					} else {
						Toast.makeText(listFragment.getActivity(),
								R.string.data_loading_ko, Toast.LENGTH_LONG)
								.show();
					}
				}

				if (this.invokedService.equalsIgnoreCase("ServiceSession")) {
					if (logOut) {
						// removing user preferences if exist
						curContext
								.getSharedPreferences(LoginActivity.PREFS_NAME,
										0).edit().clear().commit();
						// removing the Session ID
						LoginActivity.SESSION_ID = null;
						Toast.makeText(this.curContext, R.string.logout_done,
								Toast.LENGTH_LONG).show();

						Intent intent = new Intent(curContext,
								LoginActivity.class);
						curContext.startActivity(intent);
						logOut = false;

					} else {
						loginActivity.SetMAuthTask(null);
						loginActivity.showProgress(false);
						Log.i("PersonneServiceCaller", result.toString());
						if (result.equalsIgnoreCase("Wrong Password")
								|| result.equalsIgnoreCase("user unknown")) {
							// removing user preferences if exist
							loginActivity
									.getSharedPreferences(
											LoginActivity.PREFS_NAME, 0).edit()
									.clear().commit();
							if (result.equalsIgnoreCase("Wrong Password")) {
								loginActivity
										.getMPasswordView()
										.setError(
												loginActivity
														.getString(R.string.error_incorrect_password));
								loginActivity.getMPasswordView().requestFocus();
							}
							if (result.equalsIgnoreCase("user unknown")) {
								loginActivity
										.getMEmailView()
										.setError(
												loginActivity
														.getString(R.string.unknown_user));
								loginActivity.getMEmailView().requestFocus();

							}
						} else {
							/*
							 * do saving the uuid in a local variale.
							 */
							LoginActivity.SESSION_ID = result.toString();

							Toast.makeText(loginActivity,
									R.string.login_success, Toast.LENGTH_LONG)
									.show();

							Intent intent = new Intent(loginActivity,
									PersonneListActivity.class);
							loginActivity.startActivity(intent);
						}
					}
				}
				if (this.invokedService.equalsIgnoreCase("ServiceD")) {
					String[] params = PersonneUtil.createParamlist("ServiceR",
							null, null, null, null, null, null, null, null,
							null);

					new PersonneServiceCaller().execute(params);
				}
			}
		} catch (Exception e) {

		}

	}
}
